package 力扣.树.前序遍历;

public class 另一个树的子树572 {
    private boolean isSame(TreeNode a, TreeNode b) {
        if (a == b) {//都为空
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        return a.val == b.val &&
                isSame(a.left, b.left) && isSame(a.right, b.right);
    }
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if (s == t || t == null) {
            return true;
        }
        if (s == null) {
            return false;
        }
        return s.val == t.val && isSame(s, t) ||
                isSubtree(s.left, t) ||
                isSubtree(s.right, t);
    }


//前序遍历
    public boolean isSubtree3(TreeNode root, TreeNode subRoot) {
        if (root != null){//root非空
            if (root.val == subRoot.val){//比较是否是相同的树
                if (isSame2(root,subRoot)){
                    return true;
                }
            }
            //分别进入左右子树进行判断
            return isSubtree3(root.left, subRoot) || isSubtree3(root.right, subRoot);
        }
        return false;

    }

    private Boolean isSame2(TreeNode root, TreeNode subRoot) {
        if (root == subRoot){//直到都为空
            return true;
        }
        if (root != null && subRoot != null){
            if (root.val == subRoot.val){
                return isSame2(root.left, subRoot.left) && isSame2(root.right, subRoot.right);
            }
        }
        return false;
    }
}
